package com.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class SocketHandler implements  Runnable{

    private Socket socket;

    public SocketHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            RpcRequest request = (RpcRequest) objectInputStream.readObject();
            if(request != null){
                String methodName = request.getMethodName();
                Object service = Register.getService(request.getInterfaceName());
                Method method = service.getClass().getMethod(methodName,request.getParamTypes());
                Object result = method.invoke(service, request.getParameters());
                objectOutputStream.writeObject(result);
            }
        }catch (Exception e){
                e.printStackTrace();
        }finally {

        }
    }
}
